package net.pm.core.filter;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import net.pm.common.toolkit.DevConstant;

import org.apache.commons.io.FileUtils;

/**
 * 处理静态资源请求(css,js)
 * 暂未启用
 */
//@WebFilter(description = "js,css filter", urlPatterns = { "*.css","*.js" })
public class ScriptCssFilter implements Filter {

	private static final Map<String,String> FILECONTENTMAP = new HashMap<String,String>();
	private static final String LINE_SYMBOL = "\r\n";
	
    /**
     * Default constructor. 
     */
    public ScriptCssFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		final String[] filearray = request.getParameter("file").replaceAll("\\/", "/").split("\\,");
		final StringBuilder builder = new StringBuilder("");
		File file = null;
		for(String filename : filearray){
			if(!(filename.endsWith(".css") || filename.endsWith(".js")))
				continue;
			String filecontent = FILECONTENTMAP.get(filename);
			if(filecontent == null){
				file= new File(DevConstant.CLASSPATH + "../.." + filename);
				if(!file.exists())
					break;
				FILECONTENTMAP.put(filename, FileUtils.readFileToString(file,"utf-8"));
			}
			builder.append(filecontent).append(LINE_SYMBOL)
					.append("/*end of " + filename + "*/").append(LINE_SYMBOL);
		}
		response.getWriter().write(builder.toString());
		// pass the request along the filter chain
		//chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		new Thread(new CleanThread()).start();
	}
	
	/**
	 * 每半小时清空缓存
	 * @author shizeyuan
	 *
	 */
	private class CleanThread implements Runnable{
		@Override
		public void run() {
			while(true){
				try {
					Thread.sleep(1000*6*30);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				FILECONTENTMAP.clear();
			}
		}
		
	}

}
